package com.walle.ak47.commons.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SimpleRestClient {

	private static final Logger LOG = LoggerFactory.getLogger(SimpleRestClient.class);
	
	/**
     * 向指定URL发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setConnectTimeout( 1000 ); 
            connection.setReadTimeout( 2000 );
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
	
	public static String post(String url, String token, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("Accept","application/json");
            conn.setRequestProperty("Content-type","application/json; charset=UTF-8");
            conn.setRequestProperty("X-AUTH-HEADER",token);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8")) ;
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }    
	
	public static String post(String url, String token, String param, int connTimeOut, int readTimeOut) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setConnectTimeout( connTimeOut );
            conn.setReadTimeout( readTimeOut );
            conn.setRequestProperty("Accept","application/json");
            conn.setRequestProperty("Content-type","application/json; charset=UTF-8");
            if ( StringUtils.isNotBlank(token) )
            	conn.setRequestProperty("X-AUTH-HEADER",token);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8")) ;
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }   
	
	public static String post(String url, String contentType, String token, String param, int connTimeOut, int readTimeOut) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setConnectTimeout( connTimeOut );
            conn.setReadTimeout( readTimeOut );
//            conn.setRequestProperty("Accept","application/json");
            conn.setRequestProperty("Content-type", contentType+"; charset=UTF-8");
            if ( StringUtils.isNotBlank(token) )
            	conn.setRequestProperty("X-AUTH-HEADER",token);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8")) ;
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }   
	
	/**
	 * 直接使用模板进行Jaxrs调用
	 * @param url
	 * @param path
	 * @param token
	 * @param params
	 * @param templateJson
	 * @return
	 */
	public static String post( String url,String token, Map<String,String> params, String templateJson )
	{
		String result ;
		String paramJson = setParams(params, templateJson) ;
		try
		{
			result = post(url, token, paramJson) ;
		}
		catch ( Exception ex )
		{
			LOG.error( "err=>发送请求出现异常,reqJson:{}, errMsg:{}", paramJson, ex );
			return null; 
		}
		return result;
	}
	
	/**
	 * 直接使用模板进行Jaxrs调用
	 * @param url
	 * @param path
	 * @param token
	 * @param params
	 * @param templateJson
	 * @return
	 */
	public static String postMessage( String url,String token, Map<String,String> params, String templateJson, int connTimeOut, int readTimeOut )
	{
		String result ;
		String paramJson = setParams(params, templateJson) ;
		try
		{
			result = post(url, token, paramJson, connTimeOut, readTimeOut) ;
		}
		catch ( Exception ex )
		{
			LOG.error( "err=>发送请求出现异常,reqJson:{}, errMsg:{}", paramJson, ex );
			return null; 
		}
		return result;
	}
	 
	private static String setParams( Map<String,String> params, String templateJson)
	{
		String json = templateJson ;
		Iterator<Map.Entry<String, String>> iter = params.entrySet().iterator() ;
		while ( iter.hasNext() )
		{
			Entry<String, String> entry = iter.next() ;
			json = StringUtils.replace(json, entry.getKey(), entry.getValue()) ;
		}
		return json ;
	}
	
	
	/**
	 * 
	 * @param params	模板替换参数
	 * @param jsonTempleFile	json模板文件路径
	 * @param connTimeOut	连接时间
	 * @param readTimeOut	读取超时时间
	 * @return
	 * @throws Exception
	 */
	public static String postMessage( String jsonTempleFile, Map<String,String> params,  int connTimeOut, int readTimeOut )
	{
		String result ;
		String jsonTemplate;
		try {
			jsonTemplate = IOUtils.toString( new FileReader(new File(jsonTempleFile)));
		} catch (IOException e) {
			e.printStackTrace();
			return null ;
		}
		String paramJson = setParams(params, jsonTemplate) ;
		JSONObject jsonObj = JSONObject.fromObject(paramJson) ;
		String url = jsonObj.getString( "url" ) ;
		String token = jsonObj.getString( "token" ) ;
		String message = jsonObj.getString( "message" ).trim() ;
		try
		{
			result = post(url, token, message, connTimeOut, readTimeOut) ;
		}
		catch ( Exception ex )
		{
			LOG.error( "err=>发送请求出现异常,reqJson:{}, errMsg:{}", paramJson, ex );
			return null; 
		}
		return result;
	}
	
	public static Map<String,String> postMessage( String url, String token, Map<String,String> params, String templateJson )
	{
		String resp = post( url, token, params, templateJson) ;
		
		String respStr = StringUtils.replace( resp, "\"","" );
		respStr = StringUtils.replace( respStr, "{","" );
		respStr = StringUtils.replace( respStr, "}","" );
		
		
		String[] fields = StringUtils.split( respStr, ",") ;
		Map<String,String> retMap = new HashMap<String,String>() ;
		for (String string : fields) {
			String[] f = StringUtils.split(string,":") ;
			if ( f == null || f.length !=2 )
			{
				LOG.error( "无法的json->"+resp );
				return null ;
			}
			String key = f[0] ;
			if ( StringUtils.isBlank(key) )
			{
				LOG.error( "无法的json->,key为空"+resp );
				return null ;
			}
			String val = f[1] ;
			retMap.put(key, ("null".equalsIgnoreCase(val))?null:val) ;
		}
		return retMap;
	}
	
	public static void main(String[] args) 
	{
		final StringBuffer ids = new StringBuffer() ;
		long begin  = System.currentTimeMillis() ;
		ExecutorService executor = Executors.newFixedThreadPool(20) ;
		final CountDownLatch latch = new CountDownLatch(10) ;
		for( int i=0;i<10;i++)
		{
			executor.execute( new Runnable() {
				
				@Override
				public void run() {
					try
					{
						Map<String,String> params = new HashMap<String, String>() ;
						params.put( "$configId", "1" );
						params.put( "$mebId", "1" );
						params.put( "$issueType", "1" );
						Map<String,String> map = SimpleRestClient.postMessage( "http://10.100.112.50:8082/coupon-services/rest/couponServices/gain", "D81F1EA5AFE8264FACD9A5FF77B25C63",  
								params,"{\"configId\":$configId,\"mebId\":$mebId,\"issueType\":$issueType }") ;
						ids.append( map.get("id") ).append( ",") ;
					}
					finally
					{
						latch.countDown(); 
					}
				}
			});
		}
		
		try {latch.await();} catch (InterruptedException e) {e.printStackTrace();}
		
		System.err.println( "total exc time "+(System.currentTimeMillis()-begin) );
		System.err.println( "ids->"+ ids.toString());
		
		
		
		
	}
	
}
